package city.spring.modules.personnel.controller;

import city.spring.modules.ext.entity.TrainOldmanExt;
import city.spring.modules.ext.service.TrainOldmanExtService;
import city.spring.modules.oldman.entity.OldmanInfoEntity;
import city.spring.modules.oldman.service.OldmanInfoService;
import city.spring.modules.personnel.entity.EmployeeTrainingEntity;
import city.spring.modules.personnel.service.EmployeeTrainingService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Controller：培训-老人联系
 *
 * @author pxm
 * @date 2020-06-18 17:33:55
 */
@RestController
@RequestMapping("/train_oldman_ext")
public class TrainOldmanExtController extends ApiController {
    private final TrainOldmanExtService trainOldmanExtService;
    private final OldmanInfoService oldmanInfoService;
    private final EmployeeTrainingService employeeTrainingService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<TrainOldmanExt, ?>> entityOrderFields;

    public TrainOldmanExtController(TrainOldmanExtService trainOldmanExtService, OldmanInfoService oldmanInfoService, EmployeeTrainingService employeeTrainingService) {
        this.trainOldmanExtService = trainOldmanExtService;
        this.oldmanInfoService = oldmanInfoService;
        this.employeeTrainingService = employeeTrainingService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(TrainOldmanExt::getId);
        entityOrderFields.add(TrainOldmanExt::getTrainId);
        entityOrderFields.add(TrainOldmanExt::getOldmanId);
    }

    /**
     * 获取全部的 <strong>培训-老人联系</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, TrainOldmanExt entity) {
        LambdaQueryChainWrapper<TrainOldmanExt> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>培训-老人联系</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, TrainOldmanExt entity) {
        LambdaQueryChainWrapper<TrainOldmanExt> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<TrainOldmanExt> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        for (TrainOldmanExt record : page.getRecords()) {
            try {
                OldmanInfoEntity oldmanInfoEntity = oldmanInfoService.getById(record.getOldmanId());
                record.setOldmanName(oldmanInfoEntity.getOldmanName());
            } catch (Exception ignore) {
                record.setOldmanId(null);
                record.setOldmanName("< 找不到老人 >");
            }
            try {
                EmployeeTrainingEntity employeeTrainingEntity = employeeTrainingService.getById(record.getTrainId());
                record.setTrainName(employeeTrainingEntity.getName());
                // 培训开始时间
                record.setTrainStart(employeeTrainingEntity.getStart());
                // 培训结束事件
                record.setTrainEnd(employeeTrainingEntity.getEnd());
                // 培训时长，两个日期相差分钟数
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String endTime = df.format(employeeTrainingEntity.getEnd());
                String startTime = df.format(employeeTrainingEntity.getStart());
                long nm = 1000 * 60;// 一分钟的毫秒数
                long diff = df.parse(endTime).getTime() - df.parse(startTime).getTime(); // 两个日期毫秒差异
                long minutes = diff / nm;
                record.setTrainLength(minutes);
            } catch (Exception ignore) {
                record.setTrainId(null);
                record.setTrainName("< 找不到培训 >");
            }
        }

        return success(page);
    }

    /**
     * 获取一个 <strong>培训-老人联系</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        return success(trainOldmanExtService.getById(id));
    }

    /**
     * 添加一个 <strong>培训-老人联系</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody TrainOldmanExt entity) {
        trainOldmanExtService.saveTrainOldmanExt(entity);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>培训-老人联系</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable long id, @RequestBody TrainOldmanExt entity) {
        entity.setId(id);
        trainOldmanExtService.updateTrainOldmanExt(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>培训-老人联系</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        trainOldmanExtService.deleteTrainOldmanExt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>培训-老人联系</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        trainOldmanExtService.deleteTrainOldmanExt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<TrainOldmanExt> buildLambdaQuery(TrainOldmanExt entity) {
        LambdaQueryChainWrapper<TrainOldmanExt> lambdaQuery = trainOldmanExtService.lambdaQuery();
        lambdaQuery.eq(entity.getId() != null, TrainOldmanExt::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getTrainId()), TrainOldmanExt::getTrainId, entity.getTrainId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getOldmanId()), TrainOldmanExt::getOldmanId, entity.getOldmanId());
        return lambdaQuery;
    }

}
